import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

type WebsiteItem = {
  title: string;
  url: string;
  description: string;
  category: string; // 归属分类名称
  viewCount?: number;
  favoritesCount?: number;
};

// 神奇的网站分类（归属于 amazing-website 菜单）
const WEBSITE_CATEGORIES = [
  '交互体验',
  '游戏',
  '音乐',
  '知识',
  '探索',
  '科普',
  '自然',
  '物理',
  '化学',
  '数学',
  '美术',
  '天文',
  '地理',
];

// 站点清单（覆盖多学科与趣味交互：共 34 个）
const WEBSITES: WebsiteItem[] = [
  // 交互体验 / 游戏 / 音乐 / 探索 / 知识 / 科普 / 自然
  {
    title: 'Neal.fun',
    url: 'https://neal.fun/',
    description: '创意交互实验集合：地球人口、太空尺度、随机事件等，可视化极具趣味。',
    category: '交互体验',
    viewCount: 8124,
    favoritesCount: 326,
  },
  {
    title: 'Patatap',
    url: 'https://patatap.com/',
    description: '按键触发音效与视觉动画的极简音乐互动网站，随手玩很治愈。',
    category: '音乐',
    viewCount: 5218,
    favoritesCount: 210,
  },
  {
    title: 'Sandspiel',
    url: 'https://sandspiel.club/',
    description: '基于粒子效果的沙子模拟器，多种物质相互作用，呈现惊艳的物理/化学现象。',
    category: '游戏',
    viewCount: 4391,
    favoritesCount: 164,
  },
  {
    title: 'Zoomquilt',
    url: 'https://zoomquilt.org/',
    description: '无限缩放的奇幻拼图世界，沉浸式视觉探索，艺术与想象力的结合。',
    category: '交互体验',
    viewCount: 6742,
    favoritesCount: 298,
  },
  {
    title: 'Pointer Pointer',
    url: 'https://pointerpointer.com/',
    description: '为你的鼠标指针找到一个“指向它的人”，每次刷新都有惊喜与笑点。',
    category: '交互体验',
    viewCount: 3886,
    favoritesCount: 159,
  },
  {
    title: 'The True Size Of',
    url: 'https://thetruesize.com/',
    description: '国家真实大小比较工具，拖拽即可对比不同国家实际尺寸差异。',
    category: '知识',
    viewCount: 5920,
    favoritesCount: 247,
  },
  {
    title: 'Google Earth Timelapse',
    url: 'https://earthengine.google.com/timelapse/',
    description: '卫星影像查看地球几十年的时光流逝，感受城市扩张与自然变化。',
    category: '知识',
    viewCount: 7332,
    favoritesCount: 312,
  },
  {
    title: 'Incredibox',
    url: 'https://www.incredibox.com/',
    description: '趣味音乐混音器，拖拽角色生成节奏与旋律，轻松制作你的 Beat。',
    category: '音乐',
    viewCount: 4685,
    favoritesCount: 205,
  },
  {
    title: 'A Soft Murmur',
    url: 'https://asoftmurmur.com/',
    description: '白噪音混音网站，自由调配雨声风声海浪等，助你专注与放松。',
    category: '音乐',
    viewCount: 4129,
    favoritesCount: 176,
  },
  {
    title: 'Radio Garden',
    url: 'https://radio.garden/',
    description: '在地球仪上探索全球各地的电台直播，用声音旅行世界。',
    category: '探索',
    viewCount: 5613,
    favoritesCount: 231,
  },
  {
    title: 'WindowSwap',
    url: 'https://www.window-swap.com/',
    description: '随机打开世界各地的窗口，看看他人的窗外风景，感受不同文化。',
    category: '探索',
    viewCount: 4971,
    favoritesCount: 192,
  },
  {
    title: 'Zooniverse',
    url: 'https://www.zooniverse.org/',
    description: '全球最大的众包科学平台，公众参与科学研究，如星系分类、动物识别。',
    category: '科普',
    viewCount: 5360,
    favoritesCount: 218,
  },
  {
    title: 'Explore.org',
    url: 'https://explore.org/livecams',
    description: '全球野生动物与自然景观的实时摄像头，近距离观察生态与行为。',
    category: '自然',
    viewCount: 4854,
    favoritesCount: 203,
  },

  // 物理
  {
    title: 'PhET Interactive Simulations',
    url: 'https://phet.colorado.edu/',
    description: '科罗拉多大学出品的交互式物理与化学仿真，适合课堂与自学。',
    category: '物理',
    viewCount: 8420,
    favoritesCount: 354,
  },
  {
    title: 'Falstad Physics Applets',
    url: 'https://falstad.com/mathphysics.html',
    description: '经典物理可视化小程序：电路、波动、场与光学，直观理解复杂概念。',
    category: '物理',
    viewCount: 6231,
    favoritesCount: 241,
  },
  {
    title: 'The Particle Adventure',
    url: 'https://www.particleadventure.org/',
    description: '粒子物理的互动学习之旅，从基本粒子到标准模型浅显易懂。',
    category: '物理',
    viewCount: 3986,
    favoritesCount: 168,
  },

  // 化学
  {
    title: 'Ptable (交互式元素周期表)',
    url: 'https://ptable.com/',
    description: '交互式元素周期表，展示元素性质、同位素与历史等丰富信息。',
    category: '化学',
    viewCount: 7124,
    favoritesCount: 289,
  },
  {
    title: 'MolView',
    url: 'https://molview.org/',
    description: '在线分子建模与可视化工具，支持三维结构与谱图数据。',
    category: '化学',
    viewCount: 4552,
    favoritesCount: 177,
  },
  {
    title: 'PubChem',
    url: 'https://pubchem.ncbi.nlm.nih.gov/',
    description: '由 NIH 维护的化合物与生物活性数据库，科研与学习常用。',
    category: '化学',
    viewCount: 5391,
    favoritesCount: 214,
  },

  // 数学
  {
    title: 'Desmos',
    url: 'https://www.desmos.com/',
    description: '强大的在线图形计算器与活动平台，适合函数可视化与课堂互动。',
    category: '数学',
    viewCount: 8230,
    favoritesCount: 365,
  },
  {
    title: 'Wolfram Alpha',
    url: 'https://www.wolframalpha.com/',
    description: '计算知识引擎，支持数学求解、数据分析与多学科查询。',
    category: '数学',
    viewCount: 9011,
    favoritesCount: 402,
  },
  {
    title: 'Mathigon',
    url: 'https://mathigon.org/',
    description: '互动式数学学习平台，以故事与可视化呈现数学的美与逻辑。',
    category: '数学',
    viewCount: 5146,
    favoritesCount: 196,
  },
  {
    title: 'Brilliant',
    url: 'https://brilliant.org/',
    description: '以互动题与课程学习 STEM：数学、科学与计算机思维。',
    category: '数学',
    viewCount: 6821,
    favoritesCount: 271,
  },

  // 美术 / 生成艺术
  {
    title: 'Silk — Interactive Generative Art',
    url: 'https://weavesilk.com/',
    description: '指尖绘制对称的光流艺术作品，生成艺术的入门乐园。',
    category: '美术',
    viewCount: 6342,
    favoritesCount: 252,
  },
  {
    title: 'Inspirograph',
    url: 'https://nathanfriend.io/inspirograph/',
    description: '在线绘制螺旋几何艺术图案，数学与美学的碰撞。',
    category: '美术',
    viewCount: 4210,
    favoritesCount: 169,
  },
  {
    title: 'This Is Sand',
    url: 'https://thisissand.com/',
    description: '以彩色沙模拟的绘画网站，层叠渐变创造宁静美感。',
    category: '美术',
    viewCount: 3879,
    favoritesCount: 158,
  },
  {
    title: 'Google Arts & Culture',
    url: 'https://artsandculture.google.com/',
    description: '浏览全球博物馆与艺术作品，高清细节与故事导览。',
    category: '美术',
    viewCount: 7421,
    favoritesCount: 315,
  },

  // 天文
  {
    title: 'NASA Eyes on the Solar System',
    url: 'https://eyes.nasa.gov/',
    description: 'NASA 官方的太阳系交互模型，实时浏览探测器与行星轨道。',
    category: '天文',
    viewCount: 5981,
    favoritesCount: 241,
  },
  {
    title: 'Stellarium Web',
    url: 'https://stellarium-web.org/',
    description: '浏览器版的虚拟天文馆，实时星空与天体检索功能强大。',
    category: '天文',
    viewCount: 6124,
    favoritesCount: 249,
  },
  {
    title: '100,000 Stars',
    url: 'https://stars.chromeexperiments.com/',
    description: '交互式星图，探索银河中的十万颗恒星与空间尺度。',
    category: '天文',
    viewCount: 7234,
    favoritesCount: 301,
  },
  {
    title: 'Asterank',
    url: 'https://www.asterank.com/',
    description: '小行星数据库与可视化，查看轨道、价值与科学数据。',
    category: '天文',
    viewCount: 4320,
    favoritesCount: 172,
  },

  // 地理
  {
    title: 'GeoGuessr',
    url: 'https://www.geoguessr.com/',
    description: '基于街景的地理定位猜测游戏，提升地图与地貌识别能力。',
    category: '地理',
    viewCount: 6912,
    favoritesCount: 287,
  },
  {
    title: 'Earth Nullschool',
    url: 'https://earth.nullschool.net/',
    description: '全球风场与洋流的动态可视化，气象与地理的绝佳结合。',
    category: '地理',
    viewCount: 8120,
    favoritesCount: 339,
  },
];

async function getOrCreateCategory(name: string, menuId: string): Promise<string> {
  const existing = await prisma.category.findFirst({ where: { name, menuId } });
  if (existing) return existing.id;
  const created = await prisma.category.create({ data: { name, menuId } });
  return created.id;
}

async function seedAmazingWebsites() {
  console.log('🚀 开始导入神奇的网站（amazing-website）...');

  // 创建或获取“神奇的网站”菜单
  const amazingMenu = await prisma.menu.upsert({
    where: { id: 'amazing_website' },
    update: {},
    create: {
      id: 'amazing_website',
      name: '神奇的网站',
      path: '/amazing-website',
      sysCode: 'amazing-website',
      isActive: 1,
      order: 2,
    },
  });
  console.log(`📋 菜单就绪：${amazingMenu.name} (${amazingMenu.id})`);

  // 准备分类映射
  const categoryIdMap: Record<string, string> = {};
  for (const cat of WEBSITE_CATEGORIES) {
    const id = await getOrCreateCategory(cat, amazingMenu.id);
    categoryIdMap[cat] = id;
    console.log(`📂 分类就绪：${cat} -> ${id}`);
  }

  let createdCount = 0;
  for (const site of WEBSITES) {
    // 查重：按标题 + type=1（网站）
    const exists = await prisma.content.findFirst({ where: { title: site.title, type: 1 } });
    let contentId: string;
    if (exists) {
      await prisma.content.update({
        where: { id: exists.id },
        data: {
          content: site.description,
          url: site.url,
          viewCount: site.viewCount ?? exists.viewCount,
          favoritesCount: site.favoritesCount ?? exists.favoritesCount,
          coverId: exists.coverId ?? null,
          type: 1, // 1-网站
        },
      });
      contentId = exists.id;
      console.log(`✏️  已更新网站：${site.title}`);
    } else {
      const created = await prisma.content.create({
        data: {
          title: site.title,
          content: site.description,
          url: site.url,
          type: 1, // 1-网站
          viewCount: site.viewCount ?? Math.floor(1500 + Math.random() * 5000),
          favoritesCount: site.favoritesCount ?? Math.floor(50 + Math.random() * 200),
          coverId: null,
        },
      });
      contentId = created.id;
      console.log(`✅ 已创建网站：${site.title}`);
      createdCount++;
    }

    // 建立分类关联
    const categoryId = categoryIdMap[site.category];
    if (categoryId) {
      const existsRel = await prisma.contentCategory.findFirst({
        where: { contentId, categoryId },
      });
      if (!existsRel) {
        await prisma.contentCategory.create({
          data: { contentId, categoryId },
        });
      }
    }

    // 轻微延时以避免数据库瞬时拥塞（可选）
    await new Promise((r) => setTimeout(r, 100));
  }

  console.log(`\n🎉 导入完成！本次新增 ${createdCount} 个网站。`);
}

async function main() {
  try {
    await seedAmazingWebsites();
  } catch (e) {
    console.error('❌ 脚本执行失败：', e);
    process.exitCode = 1;
  } finally {
    await prisma.$disconnect();
  }
}

if (require.main === module) {
  main();
}

export { seedAmazingWebsites };